package fr.web325.servlet.api.cart;

import fr.web325.bean.Book;
import fr.web325.bean.Json;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/cart")
public class Cart extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        JSONObject json = new JSONObject();
        //3.2从session中获取购物车对象
        Map<Book, Integer> cart = (Map<Book, Integer>)session.getAttribute("cart");
        //3.3如果购物车为null,说明没有商品存储在购物车中，创建出购物车
        if (cart == null || cart.size() == 0) {
            cart = new HashMap<Book, Integer>();
            session.setAttribute("cart",cart);
            resp.getWriter().print(new Json(200,null,"购物车为空").getRespJson());
        }else{
            JSONObject cartJson = JSONObject.fromObject(cart);
            resp.getWriter().print(new Json(200,cartJson,"获取购物车列表成功").getRespJson());
        }
    }
}
